import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.util.List;
import java.util.Timer;
import java.util.concurrent.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
// 主界面
public class TrafficComparisonSystem extends JFrame {
    private final DefaultListModel<String> logModel = new DefaultListModel<>();
    private final JList<String> logList = new JList<>(logModel);
    private final JPanel devicePanel = new JPanel(new GridLayout(2, 2, 10, 10));
    private final Timer refreshTimer = new Timer(true);
    private CloudService cloudService;

    public TrafficComparisonSystem() {
        initializeUI();
        setupRefreshTimer();
    }

    private void initializeUI() {
        setTitle("交通信号控制策略对比系统 (4路口)");
        setSize(1600, 900);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout(10, 10));

        setupLogPanel();
        setupDevicePanel();
        setupControlPanel();

        log("系统准备就绪");
    }

    private void setupLogPanel() {
        logList.setFont(new Font("宋体", Font.PLAIN, 14));
        JScrollPane logScroll = new JScrollPane(logList);
        logScroll.setBorder(BorderFactory.createTitledBorder("系统日志"));
        logScroll.setPreferredSize(new Dimension(500, 0));
        add(logScroll, BorderLayout.EAST);
    }

    private void setupDevicePanel() {
        devicePanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        devicePanel.setBackground(Color.LIGHT_GRAY);
        add(devicePanel, BorderLayout.CENTER);
    }

    private void setupControlPanel() {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));

        JButton startBtn = new JButton("启动系统");
        startBtn.setFont(new Font("宋体", Font.BOLD, 18));
        startBtn.addActionListener(e -> startSystem());

        panel.add(startBtn);
        add(panel, BorderLayout.SOUTH);
    }
    //每隔500毫秒重新绘制主panel（使用IntersectionPanel绘制每一个device）
    private void setupRefreshTimer() {
        refreshTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                SwingUtilities.invokeLater(() -> {
                    if (cloudService != null) {
                        devicePanel.removeAll();
                        int vehicleCount_index=0;
                        for (EdgeDevice device : cloudService.getDevices()) {
                            devicePanel.add(new IntersectionPanel(device, vehicleCount_index++));
                        }
                        devicePanel.revalidate();
                        devicePanel.repaint();
                    }

                    int last = logModel.getSize() - 1;
                    if (last >= 0) logList.ensureIndexIsVisible(last);
                });
            }
        }, 0, 1000);
    }

    private void startSystem() {
        cloudService = new CloudService(logModel);

        // 左侧两个固定时长设备（40s绿灯/40s红灯）
        EdgeDevice downtownFixed = new EdgeDevice("DT-FIXED", "市中心主路口", false, true, logModel);
        EdgeDevice schoolFixed = new EdgeDevice("SCH-FIXED", "第一中学路口", true, true, logModel);

        // 右侧两个动态优化设备（保持原优化逻辑）
        EdgeDevice downtownDynamic = new EdgeDevice("DT-OPT", "市中心智能路口", false, false, logModel);
        EdgeDevice schoolDynamic = new EdgeDevice("SCH-OPT", "第二中学路口", true, false, logModel);

        // 注册到云端
        cloudService.registerDevice(downtownFixed);
        cloudService.registerDevice(downtownDynamic);
        cloudService.registerDevice(schoolFixed);
        cloudService.registerDevice(schoolDynamic);

        // 启动设备
        downtownFixed.start();
        downtownDynamic.start();
        schoolFixed.start();
        schoolDynamic.start();

        // 启动云端优化（只对右侧两个动态设备生效）
        cloudService.startOptimization();

        log("系统已启动: 左侧2个固定40秒路口 + 右侧2个动态优化路口");
    }

    private void log(String message) {
        SwingUtilities.invokeLater(() -> {
            logModel.addElement(LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")) +
                    " - " + message);
        });
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                new TrafficComparisonSystem().setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
}